package com.css.apps.base.common.action;

import java.io.IOException;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.css.apps.base.common.Constants;
import com.css.apps.base.security.model.SecurityParam;
import com.css.apps.base.security.service.SecurityService;
import com.css.core.configuration.Environment;
import com.css.core.model.IUser;
import com.css.db.memcached.MemCachedFactory;
import com.css.util.StringHelper;
import com.opensymphony.webwork.dispatcher.FilterDispatcher;

public class SessionFilter extends FilterDispatcher {
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		IUser user = (IUser) request.getSession().getAttribute(Environment.SESSION_LOGIN_KEY);
		// System.out.println("============timeout IUser begin=================="+user);
		if (user != null) {
			boolean flag = sessionTimeout(request, response);
			// System.out.println("============timeout flag=================="+flag);
			if (flag) {
				if (user != null) {
					request.getSession().setAttribute(user.getUserId(), null);
					MemCachedFactory.delete(Constants.ACCOUNT_LOGON + user.getUserId());
					request.getSession().setAttribute(Environment.SESSION_LOGIN_KEY, null);
				}
//				IUser user2 = (IUser) request.getSession().getAttribute(Environment.SESSION_LOGIN_KEY);
				// System.out.println("============timeout IUser end=================="+user2);
				// throw new ServletException(Messages.getString("systemMsg.sessionInvalid"));
				// response.sendRedirect("doError.action");
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	private boolean sessionTimeout(HttpServletRequest request, HttpServletResponse response) {
		String timeoutStr = SecurityService.getParamValue(SecurityParam.SESSION_TIMEOUT);
		try {
			long timeout = SecurityParam.DEFAULT_SESSION_TIMEOUT;
			if (StringHelper.isNotEmpty(timeoutStr)) {
				timeout = Integer.parseInt(timeoutStr);
			}
			timeout = timeout * 1000;
			long exp = timeout + request.getSession().getLastAccessedTime();
			if (exp < new Date().getTime()) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
